package com.yjd.comm.util;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * xss工具类
 * 
 * @author ready
 * 
 */
public class XssUtil {

	private static Logger logger = Logger.getLogger(XssUtil.class);
	private static final String XSS_WHITE_LIST_FILEPATH = "xss-white-list.txt";

	/**
	 * 过滤xss攻击
	 * 
	 * @param request
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static boolean filterXss(HttpServletRequest request) {
		boolean result = true;
		// 白名单过滤
		if (urlIsNeedValidate(ServletUtil
				.getRquestUriNotContainContextPath(request))) {
			// 过滤掉一些可能引起攻击的代码
			Map paramMap = request.getParameterMap();
			XssHTMLUtil xssHTMLUtil = new XssHTMLUtil();
			for (Iterator<String> iter = paramMap.keySet().iterator(); iter
					.hasNext();) {
				String key = iter.next();
				Object obj = paramMap.get(key);
				if (obj != null && (obj instanceof String[])) {
					String[] paraValues = (String[]) obj;
					for (int i = 0; i < paraValues.length; i++) {
						String originalValue = paraValues[i];
						paraValues[i] = xssHTMLUtil.filter(paraValues[i]);
						if (originalValue != null
								&& !originalValue.equals(paraValues[i])) {
							logger.info("xss:[key=" + key + ",originalValue="
									+ originalValue + ",value=" + paraValues[i]);
							result = false;
						}
					}
				}
			}
		} else {
			logger.debug("don't filter " + request.getRequestURI());
		}
		return result;
	}

	/**
	 * @Title: urlIsNeedValidate
	 * @Description: 判断url是否需要验证
	 * @param @param requestUrl
	 * @param @return 设定文件
	 * @return boolean 返回类型
	 * @throws
	 */
	private static boolean urlIsNeedValidate(String requestUrl) {
		List<String> list = TxtFileCacheUtil.get(XSS_WHITE_LIST_FILEPATH);
		if (list != null) {
			for (String string : list) {
				Pattern pattern = Pattern.compile(string);
				Matcher matcher = pattern.matcher(requestUrl);
				boolean b = matcher.matches();
				if (b) {
					return false;
				}
			}
		}
		return true;
	}
}
